// timer0 overflw
#include <inttypes.h>
#include <avr/io.h>
#include <avr/interrupt.h>
#include <avr/sleep.h>

#include <util/delay.h>
#include "init.h"
#include "common.h"
volatile uint8_t muxCount=0; // multiplexer counter for selecting the digit on seven seg LED display
volatile int reading=12345; // LED seven Seg display variable
volatile uint8_t ADCSem=0; // Kind of semaphore to read and write to ADC values to avoid reading of ADC during interrupt
volatile uint16_t vReflect; // voltage of reflectometer
volatile uint16_t vBattery;	// battery voltage
volatile uint8_t ADMux = 0; // adc channel selector
#define VREF 2.56

unsigned  char SEVEN_SEG[] = {
											0x3F,
											0x06,
											0x5B,
											0x4F,
											0x66,
											0x6D,
											0x7D,
											0x07,
											0x7F,
											0x6F,
											0x77,
											0x7C,
											0x39,
											0x5E,
											0x79,
											0x71
										};
										
ISR(TIMER0_COMP_vect) {
	unsigned char digit;
    // process the timer1 overflow here
	if(muxCount>4)
	{
		muxCount=0;
		while(ADCSem==1); //wait for SemPhore
		ADCSem = 1;
		reading = vReflect;
		ADCSem = 0;
	}
	
	digit = (reading /  x_to_the_n(10,muxCount))%10;
	
	SEVEN_SEGMENT_PORT = SEVEN_SEG[digit];
	
	MUX_PORT =(MUX_PORT & 0b111) /*keep PORTA0-2 untouched*/ | _BV(muxCount+3); // PORTA 3-7 used for MUX
	
	muxCount++;
}
int x_to_the_n (int x,int n);
int x_to_the_n (int x,int n)
{
    int i; /* Variable used in loop counter */
    int number = 1;

    for (i = 0; i < n; ++i)
        number *= x;

    return(number);
}


/* ADC ISR 

 * ADC conversion complete.  Fetch the 10-bit value, and feed the
 * PWM with it.
 */
ISR(ADC_vect)
{
	//adcval = ADCW;
	if(ADCSem == 0) // chk if semaphore is free
		ADCSem = 1;
	else
	{
		ADCSRA |= _BV(ADSC); /* try nextTime*/		
		return ; 
	}
  
	if(ADMux == 0)
	{
		//ADC reading to voltage conversion in milivolts pg. No. 213
		vReflect = ADCW*(int)(VREF*1000)/1024; // keeping everything in integer 
		ADMUX = _BV(REFS1) | _BV(REFS0) | _BV(MUX0); //select ADC1
		ADMux = 1;
	}
	else 
	{	
		//ADC reading to voltage conversion in milivolts pg. No. 213
		vBattery = ADCW*(int)(VREF*1000)/1024;  // keeping everything in integer 
		ADMUX = _BV(REFS1) | _BV(REFS0) ; //select ADC1
		ADMux = 0;
	}
	ADCSem = 0;
	ADCSRA |= _BV(ADSC); /* trigger next conversion*/
}
	